package ace.cmp.jmockdata.core.impl.util;

import ace.cmp.id.generator.api.LongIdGenerator;
import ace.cmp.id.generator.api.StringIdGenerator;
import com.github.jsonzou.jmockdata.DataConfig;
import com.github.jsonzou.jmockdata.JMockData;
import com.github.jsonzou.jmockdata.MockConfig;
import com.github.jsonzou.jmockdata.mocker.LongMocker;
import com.github.jsonzou.jmockdata.mocker.StringMocker;
import java.util.UUID;
import lombok.RequiredArgsConstructor;

/**
 * @author caspar
 * @date 2024/1/25 16:44
 */
@RequiredArgsConstructor
public class JMockDataUtils {
  private final LongIdGenerator longIdGenerator;
  private final StringIdGenerator stringIdGenerator;

  public <T> T mock(Class<T> cls) {
    return JMockData.mock(cls, this.getDefaultMockConfig());
  }

  public MockConfig getDefaultMockConfig() {
    MockConfig config = new MockConfig();
    final DataConfig idDataConfig = config.subConfig("id");
    StringMocker idStringMocker =
        new StringMocker() {
          @Override
          public String mock(DataConfig mockConfig) {
            if (idDataConfig == mockConfig) {
              return stringIdGenerator.get();
            }

            return UUID.randomUUID().toString();
          }
        };
    final DataConfig createTimeDataConfig = config.subConfig("createTime");
    final DataConfig updateTimeDataConfig = config.subConfig("updateTime");
    LongMocker longMocker =
        new LongMocker() {
          @Override
          public Long mock(DataConfig mockConfig) {
            if (idDataConfig == mockConfig) {
              return longIdGenerator.get();
            }
            if (createTimeDataConfig == mockConfig || updateTimeDataConfig == mockConfig) {
              return System.currentTimeMillis();
            }
            return super.mock(mockConfig);
          }
        };
    config.registerMocker(idStringMocker, String.class);
    config.registerMocker(longMocker, Long.class);
    return config;
  }
}
